<template>
  <div class="app-container">

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="140px"

    >

      <!--      <el-form-item label="设备归属类型" prop="deviceBelong" >-->
      <!--        <el-select-->
      <!--          v-model="queryParams.deviceBelong"-->
      <!--          placeholder="请选择设备归属类型"-->
      <!--          clearable-->
      <!--          filterable-->
      <!--          @change="onChangeDeviceBelong"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="dep in deviceBelongList"-->
      <!--            :key="dep.value"-->
      <!--            :label="dep.label"-->
      <!--            :value="dep.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="设备归属" prop="belongId">
        <el-select
          v-model="queryParams.belongId"
          placeholder="请选择设备归属"
          clearable
          filterable
        >
          <el-option
            v-if="queryParams.deviceBelong === '0'"
            v-for="dep in deptList"
            :key=" dep.deptId"
            :label=" dep.deptName"
            :value=" dep.deptId"
          />
          <el-option
            v-if="queryParams.deviceBelong === '1'"
            v-for="dep in  wardList "
            :key="dep.wardId "
            :label="dep.wardName "
            :value="dep.wardId "
          />
          <el-option
            v-for="dep in bedList"
            :key="dep.bedId "
            :label="dep.deptName+dep.wardName+dep.bedName"
            :value="dep.bedId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备区域" prop="belongId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择设备归属"
          clearable
          filterable
        >
          <el-option
            v-for="dep in deptList"
            :key=" dep.deptId"
            :label=" dep.deptName"
            :value=" dep.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备地址代号_序号" prop="systemId">
        <el-input
          v-model="queryParams.systemId"
          placeholder="请输入设备地址代号_序号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="modality">
        <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.modality"
          placeholder="请选择设备类别"
          clearable
          filterable
          @change="onChangeDeviceType"
        >
          <el-option
            v-for="dict in dict.type.modality_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <!-- <el-input
          v-model="queryParams.modality"
          placeholder="请输入设备类别"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="设备型号" prop="product">
        <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.product"
          placeholder="请选择设备型号"
          clearable
          filterable
        >
          <el-option
            v-for="dep in currentProductList"
            :key="dep.product"
            :label="`${dep.product}`"
            :value="dep.product"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="安装日期" prop="installDate">-->
      <!--        <el-date-picker-->
      <!--          :style="{ width: '182.5px' }"-->
      <!--          v-model="queryParams.installDate"-->
      <!--          type="date"-->
      <!--          placeholder="选择日期"-->
      <!--          format="yyyy-MM-dd"-->
      <!--          value-format="yyyy-MM-dd"-->
      <!--        >-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item label="设备状态" prop="status">
        <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.status"
          placeholder="请选择设备设备状态"
          clearable
          filterable
        >
          <el-option
            v-for="dict in dict.type.device_usage_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备运行状态" prop="warnStatus">
        <el-select
          :style="{ width: '100%' }"
          v-model="queryParams.warnStatus"
          placeholder="请选择设备设备运行状态"
          clearable
          filterable
        >
          <el-option
            v-for="dict in dict.type.device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:device:add']"
        >新增
        </el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:device:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:device:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:device:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="printData"
          v-hasPermi="['system:device:printData']"
        >打印
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="deviceList"
      :default-sort="defaultSort" @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="自增id" align="center" prop="deviceId" /> -->
      <el-table-column label="序号" align="center" width="60" type="index" :index="indexMethod">

      </el-table-column>
      <!--      <el-table-column label="设备归属类型" align="center" prop="deviceBelong">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ scope.row.deviceBelong === "0" ? "区域" : "" }}</span>-->
      <!--          <span>{{ scope.row.deviceBelong === "1" ? "网关" : "" }}</span>-->
      <!--          <span>{{ scope.row.deviceBelong === "2" ? "通道" : "" }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="设备归属" align="center" prop="belongName"/>
      <el-table-column label="设备地址代号_序号" align="center" prop="systemId" sortable="custom"
                       :sort-orders="['descending', 'ascending']"
      >
        <template slot-scope="scope">
<!--          <router-link-->
<!--            :to="{path:'/system/device-data/index',query:{systemId:scope.row.systemId,modality:scope.row.modality,unit:scope.row.unit}}"-->
<!--            class="link-type">-->
          <span style="color: blue;">{{ scope.row.systemId }}</span>
<!--          </router-link>-->
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="modality">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.modality_list"
            :value="scope.row.modality"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="product"/>
      <el-table-column label="显示的名称" align="center" prop="deviceName"/>
      <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.device_usage_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备运行状态" align="center" prop="warnStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.displayAlarm === '1' && scope.row.warnStatus === '2'" type="warning">动作</el-tag>
          <dict-tag v-else
            :options="dict.type.device_status"
            :value="scope.row.warnStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="寄存器地址" align="center" prop="registerAddress"/>
      <el-table-column label="开关量位" align="center" prop="switchingPosition"/>
      <el-table-column label="显示的内容" align="center" prop="remark" v-if="queryParams.modality=='BA'"/>

      <el-table-column label="单位" align="center" prop="unit" v-if="queryParams.modality=='BA' "/>
      <el-table-column label="输入量程" align="center" prop="inputRange"/>
      <el-table-column label="输出量程" align="center" prop="outputRange"/>
      <el-table-column label="输出源" align="center" prop="outputSource"/>
      <el-table-column
        label="设备协议"
        align="center"
        prop="protocolName"
      />
      <el-table-column label="延时时间(秒)" align="center" prop="delayTime"/>
      <el-table-column label="显示或报警" align="center" prop="displayAlarm">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.device_show_alarm"
            :value="scope.row.displayAlarm"
          />
        </template>
      </el-table-column>
      <el-table-column label="报警显示灯" align="center" prop="lightColor">

        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.chart_line_color"
            :value="scope.row.lightColor"
          />
        </template>

      </el-table-column>


      <el-table-column label="0或1定义" align="center" prop="dataDefinition"/>
      <el-table-column label="关联内部参数" align="center" prop="associateInternalParameters"/>

      <el-table-column label="有无符号" align="center" prop="symbol"/>
      <el-table-column label="乘以系数" align="center" prop="multiplyCoefficient"/>
      <el-table-column label="设定值" align="center" prop="saveValue"/>

      <el-table-column label="上限" align="center" prop="topLimit"/>
      <el-table-column label="上上限" align="center" prop="upperLimit"/>
      <el-table-column label="下限" align="center" prop="lowerLimit"/>
      <el-table-column label="下下限" align="center" prop="floorLimit"/>
      <el-table-column label="上限报警" align="center" prop="topLimitAlarm"/>
      <el-table-column label="上上限报警" align="center" prop="upperLimitAlarm"/>
      <el-table-column label="下限报警" align="center" prop="lowerLimitAlarm"/>
      <el-table-column label="下下限报警" align="center" prop="floorLimitAlarm"/>
      <el-table-column label="输出乘以系数" align="center" prop="outMultiplyCoefficient"/>
      <el-table-column label="开关量关联设备运行状态" align="center" prop="mrDeviceRunStatus"/>
      <el-table-column label="4-20mA起始偏移量" align="center" prop="dataStartPosition"/>


      <!--      <el-table-column label="安装日期" align="center" prop="installDate" />-->
      <!--      <el-table-column label="报警电话" align="center" prop="phonenumber" />-->
      <!--      <el-table-column-->
      <!--        label="最后一次离线时间"-->
      <!--        align="center"-->
      <!--        prop="lastHeartbeatTime"-->
      <!--        width="180"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{-->
      <!--            parseTime(scope.row.lastHeartbeatTime, "{y}-{m}-{d}")-->
      <!--          }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column
        width="200"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']"
          >修改
          </el-button
          >
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleSeeChange(scope.row)"-->
          <!--            v-hasPermi="['system:device:edit']"-->
          <!--          >变更记录</el-button-->
          <!--          >-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        :inline="true"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="设备类型" prop="modality">
          <el-select
            :style="{ width: '200px' }"
            v-model="form.modality"
            placeholder="请选择设备类型"
            clearable
            filterable
            @change="onChangeFormDeviceType"
          >
            <el-option
              v-for="dict in dict.type.modality_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <!-- <el-input v-model="form.modality" placeholder="请输入设备类别" /> -->
        </el-form-item>
        <el-form-item label="设备型号" prop="product">
          <el-select
            :style="{ width: '200px' }"
            v-model="form.product"
            placeholder="请选择设备型号"
            clearable
            filterable
            @change="handleChangeProduct"
          >
            <el-option
              v-for="dep in productList"
              :key="dep.product"
              :label="`${dep.product}(${dep.manufactor})`"
              :value="dep.product"
            />
          </el-select>
          <!-- <el-input v-model="form.product" placeholder="请输入设备具体型号" /> -->
        </el-form-item>

        <el-form-item label="显示的名称" prop="systemId">
          <el-input
            :style="{ width: '200px' }"
            v-model="form.deviceName"
            placeholder="请输入显示的名称"
          />
        </el-form-item>
        <el-form-item label="设备地址代号_序号" prop="systemId">
          <el-input
            :style="{ width: '200px' }"
            v-model="form.systemId"
            placeholder="请输入设备地址代号_序号"
          />
        </el-form-item>
        <el-form-item label="设备归属类型" prop="deviceBelong">
          <el-select
            :style="{ width: '200px' }"
            v-model="form.deviceBelong"
            placeholder="请选择设备归属类型"
            clearable
            filterable
          >
            <el-option
              v-for="dep in deviceBelongList"
              :key="dep.value"
              :label="dep.label"
              :value="dep.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备归属" prop="belongId">
          <!-- <el-input v-model="form.设备归属id" placeholder="请输入设备归属id" /> -->
          <el-select
            :style="{ width: '200px' }"
            v-model="form.belongId"
            placeholder="请选择设备归属"
            clearable
            filterable
          >
            <el-option
              v-if="form.deviceBelong === '0'"
              v-for="dep in deptList"
              :key=" dep.deptId"
              :label=" dep.deptName"
              :value=" dep.deptId"
            />
            <el-option
              v-if="form.deviceBelong === '1'"
              v-for="dep in  wardList "
              :key="dep.wardId "
              :label="dep.wardName "
              :value="dep.wardId "
            />
            <el-option
              v-if="form.deviceBelong === '2'"
              v-for="dep in bedList"
              :key="dep.bedId "
              :label="dep.deptName+dep.wardName+dep.bedName"
              :value="dep.bedId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备协议" prop="hospitalNumber">
          <el-select
            :style="{ width: '200px' }"
            v-model="form.hospitalNumber"
            placeholder="请选择设备协议"
            clearable
            filterable
          >
            <el-option
              v-for="dep in configurationList"
              :key="dep.id "
              :label="dep.protocolName "
              :value="dep.id +''"
            />
          </el-select>
          <!-- <el-input
            :style="{ width: '200px' }"
            v-model="form.hospitalNumber"
            placeholder="请输入设备协议"
          /> -->
        </el-form-item>

        <el-form-item label="区域" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择区域"
            filterable
          >
            <el-option
              v-for="dep in deptList"
              :key=" dep.deptId "
              :label=" dep.deptName"
              :value=" dep.deptId"
            />

          </el-select>
        </el-form-item>

        <el-form-item label="显示或报警" prop="displayAlarm">

          <el-select
            :style="{ width: '200px' }"
            v-model="form.displayAlarm"
            placeholder="请选择设备设备状态"
            clearable
            filterable
          >
            <el-option
              v-for="dict in dict.type.device_show_alarm"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <!-- <el-input v-model="form.displayAlarm" placeholder="请输入显示或报警" /> -->
        </el-form-item>
        <el-form-item label="灯的颜色" prop="lightColor">
          <el-select
            :style="{ width: '100%' }"
            v-model="form.lightColor"
            placeholder="请选择灯的颜色"
            filterable
          >
            <el-option
              v-for="dict in dict.type.chart_line_color"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>

          <!-- <el-input v-model="form.lightColor" placeholder="请输入灯的颜色" /> -->
        </el-form-item>
        <el-form-item label="0或1定义" prop="dataDefinition">
          <el-input v-model="form.dataDefinition" placeholder="请输入0或1定义"/>
        </el-form-item>
        <el-form-item label="关联内部参数" prop="associateInternalParameters">
          <el-input v-model="form.associateInternalParameters" placeholder="请输入关联内部参数"/>
        </el-form-item>
        <el-form-item label="寄存器地址" prop="registerAddress">
          <el-input v-model="form.registerAddress" placeholder="请输入寄存器地址"/>
        </el-form-item>
        <el-form-item label="开关量位" prop="switchingPosition">
          <el-input v-model="form.switchingPosition" placeholder="请输入开关量位"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
        <el-form-item label="有无符号" prop="symbol">
          <el-input v-model="form.symbol" placeholder="请输入有无符号"/>
        </el-form-item>
        <el-form-item label="乘以系数" prop="multiplyCoefficient">
          <el-input v-model="form.multiplyCoefficient" placeholder="请输入乘以系数"/>
        </el-form-item>
        <el-form-item label="设定值" prop="saveValue">
          <el-input v-model="form.saveValue" placeholder="请输入设定值"/>
        </el-form-item>

        <!--        <el-form-item label="安装日期" prop="installDate">-->
        <!--          &lt;!&ndash; <el-input v-model="form.installDate" placeholder="请输入安装日期" /> &ndash;&gt;-->
        <!--          <el-date-picker-->
        <!--            :style="{ width: '200px' }"-->
        <!--            v-model="form.installDate"-->
        <!--            type="date"-->
        <!--            placeholder="选择日期"-->
        <!--            format="yyyy-MM-dd"-->
        <!--            value-format="yyyy-MM-dd"-->
        <!--          >-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="报警电话" prop="phonenumber">-->
        <!--          <el-input-->
        <!--            :style="{ width: '200px' }"-->
        <!--            v-model="form.phonenumber"-->
        <!--            placeholder="请输入报警电话"-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item label="延时时间(秒)" prop="delayTime">
          <el-input v-model="form.delayTime" placeholder="请输入延时时间(秒)"/>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select
            :style="{ width: '200px' }"
            v-model="form.status"
            placeholder="请选择设备设备状态"
            clearable
            filterable
          >
            <el-option
              v-for="dict in dict.type.device_usage_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="输入量程" prop="inputRange">
          <el-input v-model="form.inputRange" placeholder="请输入输入量程"/>
        </el-form-item>
        <el-form-item label="输出量程" prop="outputRange">
          <el-input v-model="form.outputRange" placeholder="请输入输出量程"/>
        </el-form-item>
        <el-form-item label="输出源" prop="outputSource">
          <el-input v-model="form.outputSource" placeholder="请输入输出源"/>
        </el-form-item>
        <el-form-item label="上限" prop="topLimit">
          <el-input v-model="form.topLimit" placeholder="请输入上限"/>
        </el-form-item>
        <el-form-item label="上上限" prop="upperLimit">
          <el-input v-model="form.upperLimit" placeholder="请输入上上限"/>
        </el-form-item>
        <el-form-item label="下限" prop="lowerLimit">
          <el-input v-model="form.lowerLimit" placeholder="请输入下限"/>
        </el-form-item>
        <el-form-item label="下下限" prop="floorLimit">
          <el-input v-model="form.floorLimit" placeholder="请输入下下限"/>
        </el-form-item>
        <el-form-item label="上限报警" prop="topLimitAlarm">
          <el-input v-model="form.topLimitAlarm" placeholder="请输入上限报警"/>
        </el-form-item>
        <el-form-item label="上上限报警" prop="upperLimitAlarm">
          <el-input v-model="form.upperLimitAlarm" placeholder="请输入上上限报警"/>
        </el-form-item>
        <el-form-item label="下限报警" prop="lowerLimitAlarm">
          <el-input v-model="form.lowerLimitAlarm " placeholder="请输入下限报警"/>
        </el-form-item>
        <el-form-item label="下下限报警" prop="floorLimitAlarm">
          <el-input v-model="form.floorLimitAlarm" placeholder="请输入下下限报警"/>
        </el-form-item>
        <el-form-item label="上限关联设备运行状态" prop="topLimitDeviceRunStatus">
          <el-input v-model="form.topLimitDeviceRunStatus" placeholder="上限关联设备运行状态"/>
        </el-form-item>
        <el-form-item label="上上限关联设备运行状态" prop="upperLimitDeviceRunStatus">
          <el-input v-model="form.upperLimitDeviceRunStatus" placeholder="上上限关联设备运行状态"/>
        </el-form-item>
        <el-form-item label="下限关联设备运行状态" prop="lowerLimitDeviceRunStatus">
          <el-input v-model="form.lowerLimitDeviceRunStatus" placeholder="下限关联设备运行状态"/>
        </el-form-item>
        <el-form-item label="下下限关联设备运行状态" prop="floorLimitDeviceRunStatus">
          <el-input v-model="form.floorLimitDeviceRunStatus" placeholder="下下限关联设备运行状态"/>
        </el-form-item>
        <el-form-item label="输出乘以系数" prop="outMultiplyCoefficient">
          <el-input v-model="form.outMultiplyCoefficient" placeholder="输出乘以系数"/>
        </el-form-item>
        <el-form-item label="开关量关联设备运行状态" prop="mrDeviceRunStatus">
          <el-input v-model="form.mrDeviceRunStatus" placeholder="开关量关联设备运行状态"/>
        </el-form-item>
         <el-form-item label="4-20mA起始偏移量" prop="dataStartPosition">
          <el-input v-model="form.dataStartPosition" placeholder="4-20mA起始偏移量"/>
        </el-form-item>


        <!-- <el-form-item label="最后一次离线时间" prop="lastHeartbeatTime">
          <el-date-picker clearable
            v-model="form.lastHeartbeatTime"
            type="datetime"
            value-format="yyyy-MM-dd HH-mm-ss"
            placeholder="请选择最后一次离线时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input
            :style="{ width: '200px' }"
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板
          </el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 监控规则设定 -->
    <el-dialog
      class="blue-header"
      fullscreen
      title="设备变更记录"
      :visible.sync="openDeviceChange"
      width="70%"
      append-to-body
    >
      <log :deviceId="currentDeviceId"></log>
    </el-dialog>
  </div>
</template>

<script>
import {addDevice, delDevice, getDevice, listDevice, printData, updateDevice,} from "@/api/system/device";
import {listWard} from "@/api/system/ward";
import {listDepts} from "@/api/system/depts";
import {listBed} from "@/api/system/bed";
import {listModality} from "@/api/system/modality";
import {listConfiguration} from "@/api/system/configuration";
import {listAlarms} from "@/api/system/alarms";
import {mapState} from "vuex";

import Log from "../log";
import {getToken} from "@/utils/auth";

export default {
  name: "Device",
  dicts: [
    "chart_line_color",
    "modality_list",
    "device_status",
    "warn_status",
    "device_usage_status",
    "device_show_alarm"
  ],

  components: {
    Log,
  },
  computed: {

    // ...mapState(["app"]),
    ...mapState("app", {   // 对象形式
      alarmList: "alarmList"
    })
  },
  data() {
    const isNums = (rule, value, callback) => {
      let numberReg = /^[0-9]*$/
      if (value) {
        if (!numberReg.test(value)) {
          console.log(value)
          callback(new Error('请输入数字'))
        } else {
          console.log(value)
          callback()
        }
      } else {
        console.log(value)
        callback()
      }
    }
    return {
      flash: false,
      isAll: true,
      defaultSort: {prop: 'create_time', order: 'descending'},
      currentDeviceId: "", // 查看变更记录的时候带过去的设备id
      openDeviceChange: false,
      refreshTimer: null,
      // 查询网关参数
      queryModalityParams: {
        pageNum: 1,
        pageSize: 1000,
        deptId: null,
        wardName: null,
      },
      currentProductList: [],
      productList: [],
      // 查询网关参数
      queryWardParams: {
        pageNum: 1,
        pageSize: 1000,
        deptId: null,
        wardName: null,
      },
      wardList: [],
      // 查询区域参数
      queryDeptParams: {
        pageNum: 1,
        pageSize: 10000,
        building: null,
        floor: null,
        deptName: null,
      },
      alarmsList: [],
      deptList: [],
      // 设备端口表格数据
      bedList: [],
      // 查询参数
      queryBedParams: {
        pageNum: 1,
        pageSize: 10000,
        wardId: null,
        roomName: null,
        bedName: null,
      },
      configurationList: [],
      // 查询设备协议参数
      queryConfigurationParams: {
        pageNum: 1,
        pageSize: 1000,
        protocolName: null,
        protocolType: null,
      },
      // 设备归属类型列表
      deviceBelongList: [
        // {
        //   label: "区域",
        //   value: "0",
        // },
        // {
        //   label: "网关",
        //   value: "1",
        // },
        {
          label: "通道",
          value: "2",
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        alarm: {deviceIds: ""},
        pageNum: 1,
        pageSize: 10,
        deviceBelong: null,
        belongId: null,
        systemId: null,
        modality: null,
        product: null,
        installDate: null,
        phonenumber: null,
        lastHeartbeatTime: null,
        status: null,
        warnStatus: null,
        deviceName: null,
        deptId: null,
      },
      // 设备导入参数
      upload: {
        // 是否显示弹出层（设备导入）
        open: false,
        // 弹出层标题（设备导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的设备数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/device/importData",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceBelong: [
          {required: true, message: "设备归属类型不能为空", trigger: "blur"},
        ],
        belongId: [
          {required: true, message: "设备归属不能为空", trigger: "blur"},
        ],
        systemId: [
          {required: true, message: "设备地址代号_序号不能为空", trigger: "blur"},
        ],
        modality: [
          {required: true, message: "设备类别不能为空", trigger: "blur"},
        ],
        installDate: [
          {required: true, message: "安装日期不能为空", trigger: "blur"},
        ],
        phonenumber: [
          {required: true, message: "报警电话不能为空", trigger: "blur"},
        ],
        hospitalNumber: [
          {required: true, message: "设备协议不能为空", trigger: "blur"},
        ],
        deptId: [
          {required: true, message: "区域不能为空", trigger: "blur"},
        ]
        // topLimit:[
        //       { validator: isNums, trigger: 'blur' }
        //     ],
        //     upperLimit:[
        //       { validator: isNums, trigger: 'blur' }
        //     ],
        //     lowerLimit:[
        //       { validator: isNums, trigger: 'blur' }
        //     ],
        //     floorLimit:[
        //       { validator: isNums, trigger: 'blur' }
        //     ]
      },
    };
  },
  // watch: {
  //   $route (to, from) {
  //     // if(null== this.refreshTimer){
  //     //   this.refreshTimer = setInterval(() => {
  //     //     this.getList();
  //     //   }, 1000);
  //     // }
  //     console.log()
  //     console.log('组件：' + this.$options.name)
  //     console.log('来自：' + from.name)
  //     console.log('去往：' + to.name)
  //   }
  // },

  created() {
    console.log("created")
    this.getDeptList();
    // this.getAlarmList();
    this.getWardList();
    this.getBedList();
    // this.getModalityList();
    this.getConfigurationList();
    console.log("refreshTimer" + this.refreshTimer)
    if (null == this.refreshTimer) {
      this.refreshTimer = setInterval(() => {
        this.getList();
      }, 1000);
    } else {
      this.getList();
    }
  },
  methods: {
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    getFlash(row) {
      let f = this.alarmList.some(alarm =>
        alarm == row.deviceId
      );
      return f
    },
    getColor(row) {
      //todo 增加逻辑
      // this.flash =  (localStorage.getItem('lightSwitch')=='1')?true:false;

      // this.flash= this.alarmList.some(alarm=>
      //   alarm ==row.deviceId
      // );
      return (localStorage.getItem('lightSwitch') == '1') ? row.lightColor : ((row.warnStatus == '1' || row.warnStatus == '0') ? 'grey' : (row.lightColor))
    },
    // getFlash(){
    //   console.log(1111)
    //   console.log(localStorage.getItem('lightSwitch'))
    //   return false;
    //   // return   (localStorage.getItem('lightSwitch')=='1')?true:''
    //   // return   (localStorage.getItem('lightSwitch')=='1')?"alarmDiv":false
    // },

    indexMethod(index) {
      return index + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
    },
    // mounted() {
    //   console.log("mounted")
    //   if(null== this.refreshTimer){
    //     this.refreshTimer = setInterval(() => {
    //       this.getList();
    //     }, 1000);
    //   }
    // },
    beforeDestroy() {
      console.log("destory")
      clearInterval(this.refreshTimer);
      this.reset();
    },
    // getModalityList() {
    //   this.loading = true;
    //   listModality(this.queryModalityParams).then((response) => {
    //     this.productList = response.rows;
    //     this.loading = false;
    //   });
    // },
    getAlarmList() {
      this.loading = true;
      listAlarms().then(response => {
        this.alarmsList = response.rows;
        this.loading = false;
      });
    },
    /** 打印设备报警数据列表 */
    printData() {
      printData(this.addDateRange(this.queryParams)).then(response => {
        this.$modal.msgSuccess("打印成功");
      });
    },
    /** 查询区域列表 */
    getDeptList() {
      this.loading = true;
      listDepts(this.queryDeptParams).then((response) => {
        this.deptList = response.rows;
        console.log(this.deptList);
        this.loading = false;
      });
    },
    /** 查询网关列表 */
    getWardList() {
      this.loading = true;
      listWard(this.queryWardParams).then((response) => {
        this.wardList = response.rows;
        this.loading = false;
      });
    },
    /** 查询通道列表 */
    getBedList() {
      this.loading = true;
      listBed(this.queryBedParams).then((response) => {
        console.log(response);
        this.bedList = response.rows;
        this.loading = false;
      });
    },
    /** 查询设备协议列表 */
    getConfigurationList() {
      this.loading = true;
      listConfiguration(this.queryConfigurationParams).then((response) => {
        this.configurationList = response.rows;
        this.loading = false;
      });
    },
    /** 查询设备列表 */
    getList() {
      // this.loading = true;
      listDevice(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        // this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceBelong: null,
        belongId: null,
        systemId: null,
        modality: null,
        product: null,
        installDate: null,
        remark: null,
        phonenumber: null,
        lastHeartbeatTime: null,
        status: "0",
        warnStatus: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        manufactor: null,
        hospitalNumber: null,
        deviceName: null,
        delayTime: null,
        outputRange: null,
        inputRange: null,
        displayAlarm: null,
        lightColor: null,
        dataDefinition: null,
        associateInternalParameters: null,
        registerAddress: null,
        switchingPosition: null,
        unit: null,
        symbol: null,
        multiplyCoefficient: null,
        deptId: null,
        saveValue: null,
        outputSource: null
      };
      this.resetForm("form");
    },
    handleSeeChange(e) {
      this.currentDeviceId = e.deviceId;
      this.openDeviceChange = true;
    },
    handleChangeProduct(e) {
      const matchItem = this.productList.find((item) => item.product === e);
      if (matchItem) {
        this.form.manufactor = matchItem.manufactor;
      }
    },
    onChangeDeviceType(e) {
      this.queryParams.modalityCode = e;
      this.getList();
      // this.mounted();
      listModality({pageNum: 1, pageSize: 100000, modalityCode: e}).then(
        (response) => {
          this.currentProductList = response.rows;
          this.queryParams.product = "";
        }
      );
    },
    onChangeFormDeviceType(e) {
      listModality({pageNum: 1, pageSize: 100000, modalityCode: e}).then(
        (response) => {
          this.productList = response.rows;
          this.form.product = "";
        }
      );
    },
    // 当筛选条件改变设备归属时候
    onChangeDeviceBelong(e) {
    },
    // clickAlarm(v){
    //      //清除所有的选中
    //      this.isAll =false;
    //   this.queryParams.deviceIds=v;
    //   this.mounted();
    // },

    // clickDept(v){

    //   //清除所有的选中
    //   this.isAll =false;
    //   this.queryParams.deptId=v;
    //   this.mounted();
    // },
    handleQueryAll() {
      this.queryParams.pageNum = 1;
      this.queryParams.deptId = this.queryParams.deptId;
      this.getList();
    },
    handleQuerySelf() {
      this.queryParams.pageNum = 1;
      this.queryParams.deviceIds = (null == this.queryParams.alarm.deviceIds) ? "" : this.queryParams.alarm.deviceIds.split(":")[1];
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.deviceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids;
      getDevice(deviceId).then(async (response) => {
        // 查询设备型号
        await this.onChangeFormDeviceType(response.data?.modality);
        setTimeout(() => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备";
        }, 500);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal
        .confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？')
        .then(function () {
          return delDevice(deviceIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/device/export",
        {
          ...this.queryParams,
        },
        `device_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/device/importTemplate",
        {},
        `device_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },

  beforeRouteLeave(to, from, next) {
    // Perform any cleanup or actions here
    // before leaving the current route
    // Call the beforeDestroy() method
    this.beforeDestroy();
    // Continue with the route navigation
    next();
  },
};
</script>
<style scoped>
.tip {

  line-height: 10px;
  margin: 2px;
  padding: 1px;
  color: rgb(52 88 124 / 75%);

  border-radius: 20% 0% 40% 0%;
  background-color: rgb(122 132 216 / 19%);
  position: absolute;
  float: left;
  margin: 2px;
}

.blue-header >>> .el-dialog__header {
  background-color: #20a0ff;
  padding-bottom: 20px;
}

.blue-header >>> .el-dialog__title {
  color: #fff;
}

.blue-header >>> .el-dialog__close {
  color: #fff;
}

.selected {
  color: #1890ff;
  border-color: #badeff;
  background-color: #e8f4ff
}

::v-deep .el-table__body-wrapper::-webkit-srollbar-track {
  background-color: rgba(255, 255, 255, 0);
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  height: 12px;
  width: 10px;
  opacity: 0.5;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 15px;
  background-color: #a39f9f;
}

.alarmDiv {
  display: block;
  /* width: 1vw;
  height: 1vw;
  border-radius:50px;
background-color: red;  */
  -webkit-animation-name: imageAnim;
  -webkit-animation-duration: 0.5s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-direction: alternate;
  -webkit-animation-timing-function: ease;
  -webkit-animation-play-state: running;
}

@-webkit-keyframes imageAnim {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
  }
}

</style>
